import React, { Component } from 'react'
import PubSub from 'pubsub-js'

export default class Search extends Component {

     search = async() => {
        const { keywordElement: { value: keyword } } = this
        // 进入等待状态
        PubSub.publish('List', { loading: true, isFirst: false });
        /* axios.get(`http://localhost:3000/api1/search/users?q=${data}`).then(response=>{
            console.log('请求成功',response.data);
            const {items} = response.data;
            const userList = items.map((userObj)=>{
                return {id:userObj.id,avator:userObj.avatar_url,name:userObj.login,home:userObj.html_url}
            })
            PubSub.publish('List',{userList:userList,loading:false})
        },error=>{
            console.log(error);
            // 这里需要注意，error回调函数返回的是error对象，不能直接传入
            PubSub.publish('List',{loading:false,error:error.message})
        }) */

        /* 优化前
        fetch(`/api1/search/users?q=${data}`).then(
            response => {
                console.log('请求服务器成功了...');
                return response.json();
            },error=>{
                console.log('请求服务器失败了...');
                // 返回一个空的 Promise 对象，否则代码会继续往下走
                return new Promise(()=>{})
            }
        ).then(
            response => {
                console.log('请求数据成功',response)
            },error => {
                console.log('获取数据失败',error)
            }
        ) */

        /* 
           上面这种方式虽然可以成功发送fetch请求，但是比较繁琐，需要链式调用then方法，手动处理多种异常情况
           实际上，我们可以用catch来处理所有异常，结合 await async 关键字来使用
            优化后：*/
        try {
            const response = await fetch(`/api1/search/users?q=${keyword}`); // fetch将会返回一个Promise对象
            const data = await response.json()
            PubSub.publish('List', { userList: data.items, loading: false })
        } catch (error) {
            console.log('请求出错', error);
            PubSub.publish('List',{loading:false,error:error.message});
        }
    }

    render() {
        return (
            <div>
                <section className="jumbotron">
                    <h3 className="jumbotron-heading">Search Github Users</h3>
                    <div>
                        <input ref={c => this.keywordElement = c} type="text" placeholder="enter the name you search" />&nbsp;
                        <button onClick={this.search}>Search</button>
                    </div>
                </section>
            </div>
        )
    }
}
